package com.qf.web.controller;

import com.qf.domain.Goods;
import com.qf.domain.PageBean;
import com.qf.domain.User;
import com.qf.service.GoodsService;
import com.qf.service.impl.GoodsServiceImpl;
import com.qf.util.StringUtil;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


@WebServlet("/goodsservlet")
@MultipartConfig(maxFileSize = 1024*1024,maxRequestSize = 1024*1024*1024)
public class GoodsServlet extends BaseServlet {
    //商品分页
    public String getGoodsListByTypeId(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");//设置编码
        //1·获取前端数据
        //商品类别
        String typeId = request.getParameter("typeId");
        //商品页面
        String pageNum = request.getParameter("pageNum");
        //获取页大小
        String pageSize = request.getParameter("pageSize");
        //商品名称
        String goodsName = request.getParameter("goodsName");
        System.out.println("goodsName"+goodsName);
        //2·校验数据
        int page_num=1;
        int page_size=8;
        try {
            if(!StringUtil.isEmpty(pageNum)){
                page_num = Integer.parseInt(pageNum);
                if(page_num<1){
                    page_num=1;
                }
            }
            if(!StringUtil.isEmpty(pageSize)){
                page_size = Integer.parseInt(pageSize);
                if(page_size<1 || page_size>50){
                    page_size=8;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //封装条件
        StringBuilder where = new StringBuilder(" where 1=1 ");
        List<Object>params = new ArrayList<>();
        if(!StringUtil.isEmpty(typeId)){//不等于
            where.append(" and typeid=? ");
            params.add(typeId);
        }
        if(!StringUtil.isEmpty(goodsName)){
            where.append(" and name like ? ");
            params.add("%"+goodsName+"%");
        }
        //没有条件不执行查询
        if(params.size()<=0){
            return "/goodsList.jsp";
        }
        //创建业务对象
        GoodsService goodsServlice = new GoodsServiceImpl();
        try {
            PageBean<Goods> pageBean = goodsServlice.findByPage(page_num,page_size,where.toString(),params);
            request.setAttribute("typeId",typeId);
            request.setAttribute("goodsName",goodsName);
            request.setAttribute("pageBean",pageBean);
            return "/goodsList.jsp";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:/index.jsp";
    }
    //商品详情
    public String getGoodsById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //通过id查商品
            //
            //1`获取前端数据
            String id = request.getParameter("id");
            //2`判断商品id
            if(StringUtil.isEmpty(id)){
                request.setAttribute("msg","商品id不能为空");
                return "/message.jsp";
            }
            //3`查询
            GoodsService goodsServlet = new GoodsServiceImpl();
            try {
                Goods goods =  goodsServlet.findById(Integer.parseInt(id));
                request.setAttribute("goods",goods);
                return "/goodsDetail.jsp";//商品详情页
            } catch (Exception e) {
                e.printStackTrace();
                request.setAttribute("msg","查询失败");
                return "/message.jsp";
            }
        }
    //后台添加商品
    public String addGoods(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       //设置编码
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        //获取前端数据
        String name = request.getParameter("name");
        String typeid = request.getParameter("typeid");
        String pubdate = request.getParameter("pubdate");
        String price = request.getParameter("price");
        String star = request.getParameter("star");
        String intro = request.getParameter("intro");
        //获取图片
        Part picture = request.getPart("picture");
        //验证
        if(StringUtil.isEmpty(name)){
            request.setAttribute("msg","商品名不能为空");
            return "admin/addGoods.jsp";
        }
        if(StringUtil.isEmpty(typeid)){
            request.setAttribute("msg","商品类型不能为空");
            return "admin/addGoods.jsp";
        }
        if(StringUtil.isEmpty(pubdate)){
            request.setAttribute("msg","上架时间不能为空");
            return "admin/addGoods.jsp";
        }
        if(StringUtil.isEmpty(price)){
            request.setAttribute("msg","价格不能为空");
            return "admin/addGoods.jsp";
        }
        if(StringUtil.isEmpty(star)){
            request.setAttribute("msg","热销度不能为空");
            return "admin/addGoods.jsp";
        }
        if(StringUtil.isEmpty(intro)){
            request.setAttribute("msg","商品介绍不能为空");
            return "admin/addGoods.jsp";
        }
        //商品类型判断(商品类型id)
        int type_id = Integer.parseInt(typeid);
        if(type_id <= 0){
            request.setAttribute("msg","请选择合适类型");
            return "admin/addGoods.jsp";
        }
        //图片的处理
        //保存图片
        //2 IE获取文件名问题（截取文件名）修改
        String dis=picture.getHeader("Content-Disposition");
        String filename=dis.substring(dis.lastIndexOf("filename=")+10,dis.length()-1);
        filename=filename.substring(filename.lastIndexOf("//")+1);
        String uuidfilename=null;
        try {
            //获取后缀
            if(!filename.equals("")){
                //保存图片
                //生成新的文件名
                String basepath = request.getServletContext().getRealPath("WEB-INF"+ File.separator+"images");
                File dir = new File(basepath);
                if(!dir.exists()){
                    dir.mkdirs();
                }
                //获取后缀
                String ext = filename.substring(filename.lastIndexOf(".")+1);
                uuidfilename= UUID.randomUUID().toString().replace("-"," ");
                uuidfilename=uuidfilename+"."+ext;
                picture.write(basepath+File.separator+uuidfilename);
                picture.delete();//删除缓存
                System.out.println("图片上传成功");
            }
            //把图片添加到数据库
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Goods goods = new Goods(0,name,sdf.parse(pubdate),uuidfilename,new BigDecimal(price),Integer.parseInt(star),intro,Integer.parseInt(typeid));
            GoodsService goodsService = new GoodsServiceImpl();
            goodsService.add(goods);
            response.getWriter().write("<script>alert('添加成功');window.location='admin/addGoods.jsp'</script>");
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("<script>alert('添加失败');window.location='admin/addGoods.jsp'</script>");
        }
        return null;
    }
    //后台查看商品
    public String goodsTypeList(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
        //编码设置
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        //判断用户是否登录
        User user = (User) request.getSession().getAttribute("user");
        if(user == null){
            return "redirect:/login.jsp";
        }
        //创建业务对象
        GoodsService goodsService = new GoodsServiceImpl();
        return null;
    }
}


